/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 用于生成Java Model类
 * @author yuanguozheng
 */
var path = require('path');
var template = require('art-template');
var moment = require('moment');
var config = require('../utils/config');
var fileutil = require('../utils/fileutil');

/**
 * 利用Java模板进行渲染
 *
 * @param {Object} data 传入的参数
 * @param {string} basePath 基本路径
 * @param proj
 * @param ns
 * @param callback
 */
function renderAndWrite(data, basePath, proj, ns, mapping, callback) {
    if (data == null) {
        return;
    }
    template.config('escape', false);
    template.config('extname', '.tmpl');
    template.config('base', path.join(__dirname, '../templates'));
    var realPath = path.join(basePath, proj, ns);
    if (!fileutil.mkdir(realPath)) {
        return;
    }
    var year = moment().format('YYYY');
    for (var i = 0; i < data.length; i++) {
        var renderData = {
            namespace: ns,
            proj: proj,
            data: data[i],
            year: year,
            mapping: mapping,
            usings: getUsing(data[i].member)
        };
        var output = template('cs', renderData);
        fileutil.writeToFile(realPath, renderData.data.cls + '.cs', output);
        if (i == data.length - 1) {
            callback();
        }
    }
}

function getUsing(item) {
    var usings = [];
    item.forEach(function (i) {
        if (i.type.toString().startsWith('List<')) {
            usings.push('using System.Collections.Generic;');
        }
        if (i.type.toString().startsWith('ObservableCollection<')) {
            usings.push('using System.Collections.ObjectModel;');
        }
    });
    return usings;
}

module.exports = renderAndWrite;